package com.triptogether.shoppinglist.adapters;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;

import com.triptogether.R;
import com.triptogether.utils.db.DBManager;
import com.triptogether.utils.db.models.Product;
import com.triptogether.utils.log.Logger;

public class ProductsListAdapter extends BaseAdapter {

	private final String TAG = Logger.makeLogTag(this.getClass());

	private List<Product> productsList;
	private LayoutInflater mInflater;
	private Context context;

	public ProductsListAdapter(Context context, List<Product> products) {
		this.productsList = (ArrayList<Product>) products;
		this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public ProductsListAdapter(Context context, long shoppingListId) {
		this(context, (ArrayList<Product>) DBManager.getInstance(context).findProductsByShoppingListId(shoppingListId));
	}

	/**
	 * Generate the view that represents the list. Choose the layout that should
	 * be displayed according to the {@link Product}
	 */
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// Check if the convert view is null, and inflate it when necessary
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.list_item_product, null);
			final EditText productNameEditText = (EditText)convertView.findViewById(R.id.edittext_product_name);
			final CheckBox isBoughtCheckBox = (CheckBox)convertView.findViewById(R.id.checkbox_product_is_bought);
			final ImageButton deleteImageButton = (ImageButton)convertView.findViewById(R.id.button_delete_product);
			
			
			// Set on click listener
			isBoughtCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					Product product = (Product) getItem(position);
					product.setBought(isChecked);
					updateProductOnDB(product);
					productNameEditText.setEnabled(!isChecked);
				}
			});
			
			productNameEditText.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				}
				
				@Override
				public void afterTextChanged(Editable s) {
					Product product = productsList.get(position);
					product.setProductName(productNameEditText.getText().toString());
					updateProductOnDB(product);
				}
			});
			
			deleteImageButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					deleteProductOnDB(position);
				}
			});
		}

		try {
			final Product product = productsList.get(position);

			// Initialize the view UI
			initItemViewUI(convertView, product);

		} catch (Exception e) {
			Logger.LOGE(TAG, e.getMessage());
		}

		return convertView;
	}
	
	private void updateProductOnDB(Product product) {
		DBManager.getInstance(context).updateProduct(product);
	}
	
	private void deleteProductOnDB(int position) {
		Product product = remove(position);
		DBManager.getInstance(context).deleteProduct(product);
	}

	private void initItemViewUI(View view, Product product) {
		// initialize the views members
		CheckBox productCheckBox = (CheckBox) view.findViewById(R.id.checkbox_product_is_bought);
		EditText productTextView = (EditText) view.findViewById(R.id.edittext_product_name);

		// set the values into the views
		productTextView.setText(product.getProductName());
		productCheckBox.setChecked(product.isBought());
	}

	public void add(Product newProduct) {
		productsList.add(newProduct);
		notifyDataSetChanged();
	}
	
	public Product remove(int position) {
		Product removedProduct = productsList.remove(position);
		notifyDataSetChanged();
		return removedProduct;
	}

	@Override
    public int getCount() {
		return productsList.size();
    }

	@Override
    public Object getItem(int position) {
		return productsList.get(position);
    }

	@Override
	public long getItemId(int position) {
		return productsList.get(position).getId();
	}

}
